package org.bigjava.novelplatform.common.handlerInterceptor;

import lombok.extern.slf4j.Slf4j;
import org.bigjava.novelplatform.common.enums.UserRole;
import org.bigjava.novelplatform.common.exception.UserActionException;
import org.bigjava.novelplatform.vo.UserInfoVo;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static org.bigjava.novelplatform.common.constant.NovelInfoConstant.SESSION_USER;
import static org.bigjava.novelplatform.common.exception.ExceptionCodeMessage.NOT_WRITER;
import static org.bigjava.novelplatform.common.exception.ExceptionCodeMessage.UN_LOGIN;

/**
 * 检查用户的作者身份
 * @author ykh
 * @create 2022-05-10 22:25
 */
@Slf4j
@Order(Integer.MAX_VALUE)
public class WriterHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.matches(request.getMethod())) {
            return true;
        }
        UserInfoVo UserInfo = (UserInfoVo) request.getSession().getAttribute(SESSION_USER);
        if (!UserInfo.getType().equalsIgnoreCase(UserRole.WRITER.toString())) {
            throw new UserActionException(NOT_WRITER);
        }
        return true;
    }
}
